﻿var multichoice = multichoice || { };
multichoice.ajax = multichoice.ajax || { };

// Json Proxy Class
// parameters:
//      request :: the request details for the proxy
multichoice.ajax.jsonProxy = function(request) {

    this.Request = request;
    this.cache = new Cache("ajaxResponses");
    this.user = new User();

    // Begin the async request
    this.BeginRequest = function() {
        var requestType = "POST";

        if (this.Request.Type) {
            requestType = this.Request.Type;
        }

        var ajaxOptions = {
            url: this.Request.Url,
            type: requestType,
            dataType: "JSON",
            data: JSON.stringify(this.Request.Data),
            complete: this.EndRequest,
            contentType: "application/json; charset=\"utf-8\"",
            context: this
        };

        if (this.user.Schema()) {
            var canonicalValue = this.user.Schema().CanonicalValue;
        }

        ajaxOptions.headers = { komodoUser: this.user.UserName(), komodoSchema: canonicalValue };


        //Cache
        if (request.Cache) {
            var key = this.Request.Url + JSON.stringify(this.Request.Data);
            if (this.cache.containsKey(key)) {
                this.respond(this.cache.get(key).Response, "success");
            } else {
                $.ajax(ajaxOptions);
            }
        } else {
            $.ajax(ajaxOptions);
        }
    };

    // End the async request routing the various responses to their callback handlers
    this.EndRequest = function(xmlHttpRequest, status) {
        var response = JSON.parse(xmlHttpRequest.responseText);

        if (xmlHttpRequest.status == 401) {
            alert("Publishing Authentication Failure Message, Remove when we have something that subscribes to this message.");
            amplify.publish("AuthenticationFailure", { Message: response.ErrorText });
        } else if (request.Cache) {
            var key = this.Request.Url + JSON.stringify(this.Request.Data);
            var duration = request.CacheDuration || 60;
            this.cache.put(key, { Duration: duration, CacheTime: Date(), Response: response });
        } else {
            this.respond(response, status);
        }
    };

    this.respond = function(response, status) {
        if (status == "success") {
            if (this.Request.OnSuccess) {

                if (this.Request.CallbackContext) {
                    this.Request.CallbackContext.OnSuccess = this.Request.OnSuccess;
                    this.Request.CallbackContext.OnSuccess(response);
                } else {
                    this.Request.OnSuccess(response);
                }
            }
        } else if (status == "error") {
            if (this.Request.OnError) {
                if (this.Request.CallbackContext) {
                    this.Request.CallbackContext.OnError = this.Request.OnError;
                    this.Request.CallbackContext.OnError(response);
                } else {
                    this.Request.OnError(response);
                }
            } else {
                if (window.KomodoUIServices) {
                    if (window.KomodoUIServices.ModalDialogService) {
                        window.KomodoUIServices.ModalDialogService(
                            {
                                Message: response.ErrorText,
                                Title: "Error",
                                Buttons: {
                                    Ok: null
                                }
                            });
                    }
                } else {
                    alert(response.ErrorText);
                }

            }
        }
    };
};